package com.zy.web.controller.reverse;

import com.zy.common.core.domain.AjaxResult;
import com.zy.common.exception.ServiceException;
import com.zy.common.utils.SecurityUtils;
import com.zy.common.utils.StringUtils;
import com.zy.reverse.service.IReverseIntService;
import com.zy.system.service.ISysConfigService;
import com.zy.utils.ParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author javachen
 * @description ReverseIntController
 */
@RestController
@CrossOrigin
@RequestMapping("/reverse")
public class ReverseIntController {

    @Autowired
    private IReverseIntService reverseIntService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 执行get请求
     * @return
     */
    @GetMapping(value = "/{prefix}/{name}")
    public AjaxResult reverseIntGet(@PathVariable("prefix") String prefix, @PathVariable("name") String name, HttpServletRequest request){
        //get请求参数=url参数
        Map<String, Object> inputParamMap = ParamUtils.getRequestParamMap(request);
        return commonMethod(prefix, name, inputParamMap);
    }

    /**
     * 执行post请求
     * @return
     */
    @PostMapping(value = "/{prefix}/{name}")
    public AjaxResult reverseIntPost(@PathVariable("prefix") String prefix, @PathVariable("name") String name, @RequestBody Map<String,Object> inputParamMap, HttpServletRequest request){
        //post请求参数=url参数+requestBody参数
        inputParamMap.putAll(ParamUtils.getRequestParamMap(request));
        return commonMethod(prefix, name, inputParamMap);
    }

    /**
     * get与post请求公共处理方法
     * @return
     */
    public AjaxResult commonMethod( String prefix, String name, Map<String,Object> inputParamMap){

        String isCheckToken = configService.selectConfigByKey("sys.check.token");

        //打开token验证
        if(StringUtils.isEmpty(isCheckToken)||"on".equals(isCheckToken)){
            SecurityUtils.getLoginUser();
        }

        String[] nameSplitArr = name.split(",");

        if(nameSplitArr.length>5){
            throw new ServiceException("合并请求不能超过五个");
        }

        if(nameSplitArr.length==1){
            return AjaxResult.success(reverseIntService.executeMethod(prefix,name,inputParamMap));
        }

        Map<String, Object> resultMap = new HashMap<>();

        for (int i = 0; i < nameSplitArr.length; i++) {
            Map<String,Object>  resultMapTemp = (Map<String, Object>) reverseIntService.executeMethod(prefix, nameSplitArr[i], inputParamMap);
            resultMap.put("result"+(i+1),resultMapTemp.get("result"));
        }

        return AjaxResult.success(resultMap);
    }

}
